import React, {Component} from 'react'
import {Button, Col, Divider, Row} from 'antd'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import QuizzesTable from './quizzes-table'

import SearchBox from '../common/search-box'
import {FormattedMessage} from 'react-intl'
import {deleteQuiz, getSurveyQuizzes} from "../../actions/survey-quiz"
import ImportBasicQuizModal from "../common/import_basic_quiz_modal";
import ImportSurveyQuizModal from "../common/import_survey_quiz_modal";

class codingQuizzes extends Component {
  state = {
    page: 1,
    pageSize: 10,
    searchConditions: {}
  }

  componentDidMount = () => {
    this.props.getSurveyQuizzes()
  }

  onChange = page => {
    this.setState({page})
    const {pageSize, searchConditions} = this.state
    this.props.getSurveyQuizzes(page, pageSize, searchConditions)
  }

  onSearch = searchConditions => {
    const defaultPage = 1
    this.setState({searchConditions})
    const {pageSize} = this.state
    this.props.getSurveyQuizzes(defaultPage, pageSize, searchConditions)
  }

  addQuiz = () => {
    this.props.history.push(`/surveyQuizzes/new`)
  }

  deleteQuiz = quizId => {
    this.props.deleteQuiz(quizId)
  }

  render() {
    const {surveyQuizzesPageable} = this.props
    const {page, pageSize} = this.state
    const pagination = {
      current: page,
      total: surveyQuizzesPageable.totalElements,
      pageSize: pageSize,
      onChange: (page) => {
        this.onChange(page, pageSize)
      }
    }
    return (
      <div>

        <Row>
          <Col span={3}>
            <Button type='primary' onClick={this.addQuiz}><FormattedMessage id='新增'/></Button>
          </Col>
          <Col span={3}>
            <ImportSurveyQuizModal
              refreshQuizzes={this.props.getSurveyQuizzes}/>
          </Col>
        </Row>
        <Row>
          <SearchBox onSearch={this.onSearch}/>
        </Row>
        <Divider type='horizontal'/>
        <QuizzesTable dataSource={surveyQuizzesPageable.content} pagination={pagination}
                      onDeleteQuiz={this.deleteQuiz}
        />
      </div>
    )
  }
}

const mapStateToProps = ({surveyQuizzesPageable}) => ({
  surveyQuizzesPageable
})

const mapDispatchToProps = dispatch => ({
  getSurveyQuizzes: (page, pageSize, searchConditions) => dispatch(getSurveyQuizzes(page, pageSize, searchConditions)),
  deleteQuiz: (quizId) => dispatch(deleteQuiz(quizId))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(codingQuizzes))
